package com.hurl.waguji.base.dataprocess;

import java.util.Date;

import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Restrictions;

import com.hurl.library.util.DateUtils;
import com.hurl.waguji.base.dao.HibernateDao;
import com.hurl.waguji.persistence.DownloadResultBO;

public class ProcessHelper {
	/**
	 * 保存下载任务的执行结果。
	 * @param result
	 * @param dao
	 */
	public static void saveProcessResult(ProcessResult result,HibernateDao dao){
		DownloadResultBO bo = new DownloadResultBO();
		bo.setDownloadId(result.getId().getId());
		bo.setDownloadTitle(result.getTitle());
		bo.setDownloadCount(result.getCount());
		bo.setRq(result.getRq());
		bo.setSuccess(result.isSuccess());
		bo.setStartTime(result.getStartTime());
		bo.setEndTime(result.getEndTime());
		bo.setError((result.getError()==null?null:result.getError().getMessage()));
		dao.save(bo);
	}
	
	/**
	 * 等同于isAlreadyProcessed，只是返回方法不一样。
	 * @param downloadId
	 * @param rq
	 * @param dao
	 * @throws ProcessException
	 */
	public static void validateAlreadyProcessed(String downloadId,Date rq,HibernateDao dao)throws ProcessException{
		if(isAlreadyProcessed(downloadId,rq,dao)){
			throw new ProcessException(DateUtils.formatDate(rq, DateUtils.FORMAT_DATE_CN)+"的数据已经处理过！");
		}
	}
	/**
	 * 检查某个下载任务是否已经完成。
	 * @param downloadId
	 * @param rq
	 * @return
	 */
	public static boolean isAlreadyProcessed(String downloadId,Date rq,HibernateDao dao){
		ScrollableResults results = dao.createCriteria(DownloadResultBO.class)
		.add(Restrictions.eq("downloadId", downloadId))
		.add(Restrictions.eq("success", Boolean.TRUE))
		.add(Restrictions.eq("rq", rq)).setReadOnly(true).scroll();
		return results.next();
	}
}
